import { Service } from 'egg';
import { Advert } from '../model/Advert';

class AdvertService extends Service {
    /**
     * 查询广告列表
     */
    public async searchAdvertList(param: any) {
        const submitData: any = {};
        const status = param.status;
        if (status == 1) {
            submitData.advert_status = '1';
        } else if (status == 2) {
            submitData.advert_status = '2';
        }
        submitData.is_delete = '1';
        const resultAdvert: any = await this.ctx.model.Advert.findAll<Advert>({
            attributes: ['advert_id', 'advert_order', 'advert_type', 'advert_partment', 'advert_status', 'advert_picture'],
            where: submitData,
            order: [['advert_order', 'ASC']],
        });
        if (resultAdvert.length <= 0) {
            throw new Error(JSON.stringify({ code: 2, msg: '没有数据' }));
        }
        const advertList: any = [];
        for (let i = 0; i < resultAdvert.length; i++) {
            const item: any = {};
            item.advert_id = resultAdvert[i].advert_id;
            item.advert_order = resultAdvert[i].advert_order;
            item.advert_type = resultAdvert[i].advert_type;
            item.advert_partment = resultAdvert[i].advert_partment;
            item.advert_status = resultAdvert[i].advert_status;
            item.advert_picture = resultAdvert[i].advert_picture;
            const advert_type = Number(resultAdvert[i].advert_type);
            if (advert_type === 1) {
                const advert_partment = resultAdvert[i].advert_partment;
                const queryStr = `select activity_title,activity_cover from t_activity where activity_id=:activity_id`;
                const resultActivity = await this.ctx.model.query(queryStr,
                    {
                        type: this.ctx.model.QueryTypes.SELECT,
                        replacements: { activity_id: advert_partment }
                    }
                );
                item.activity_title = resultActivity[0].activity_title;
                item.activity_cover = resultActivity[0].activity_cover;
            }
            advertList.push(item);
        }
        return advertList;
    }

    /**
     * 新增广告
     * @param param 
     */
    public async createAdvert(param: any) {
        const submitData: any = {};
        submitData.advert_id = this.ctx.helper.genUUID();
        submitData.advert_order = (await this.ctx.model.Advert.count({ where: { is_delete: '1' } })) + 1;
        submitData.advert_type = param.advert_type;
        submitData.advert_partment = param.advert_partment;
        submitData.advert_picture = param.advert_picture;
        submitData.advert_status = '1';
        submitData.is_delete = '1';
        const resultAdvert = await this.ctx.model.Advert.create(submitData);
        if (!resultAdvert) {
            throw new Error(JSON.stringify({ code: 2, msg: '新增失败' }));
        }
    }

    /**
     * 修改广告
     * @param param 
     */
    public async updateAdvert(param: {}) {
        let submitData: any = {};
        const advert_id = param['advert_id'];
        for (const i in param) {
            if (i === 'advert_id') {
                continue;
            }
            submitData[i] = param[i];
        }
        const resultAdvert = await this.ctx.model.Advert.update(submitData, { where: { advert_id } });
        if (resultAdvert[0] <= 0) {
            throw new Error(JSON.stringify({ code: 2, msg: '修改失败' }));
        }
    }

    /**
     * 启用、停用广告
     * @param advert_id 
     * @param type 
     */
    public async startAndStopAdert(advert_id: string, type: string) {
        const resultAdvert = await this.ctx.model.Advert.update({ advert_status: type }, { where: { advert_id } });
        if (resultAdvert[0] <= 0) {
            throw new Error(JSON.stringify({ code: 2, msg: '操作失败' }));
        }
    }

    /**
     * 上移、下移广告
     * @param advert_id 
     * @param advert_order 
     * @param type 
     */
    public async removeAdvert(advert_id: string, advert_order: number, type: number) {
        const allCount = await this.ctx.model.Advert.count({ where: { is_delete: '1' } });
        if (advert_order === 1 && type === 1) {
            throw new Error(JSON.stringify({ code: 2, msg: '已到达顶部，不能上移' }));
        } else if (advert_order === allCount && type === 2) {
            throw new Error(JSON.stringify({ code: 2, msg: '已到达底部，不能下移' }));
        }
        let changeOrder: number = -1;
        if (type === 1) {
            changeOrder = advert_order - 1;
        } else if (type === 2) {
            changeOrder = advert_order + 1;
        }
        const checkAdvert = await this.ctx.model.Advert.findOne<Advert>({ where: { advert_id, is_delete: '1', advert_order } });
        if (!checkAdvert) {
            throw new Error(JSON.stringify({ code: 2, msg: '未找到当前操作的广告数据' }));
        }
        const tran = await this.ctx.model.transaction();
        try {
            const targetAdvert: any = await this.ctx.model.Advert.findOne<Advert>({ attributes: ['advert_id'], where: { advert_order: changeOrder, is_delete: '1' } });
            const targetAdvertId = targetAdvert['advert_id'];
            if (!targetAdvertId) {
                throw new Error('未找到目标广告数据');
            }
            const resultData = await this.ctx.model.Advert.update({ advert_order: changeOrder }, { where: { advert_id }, transaction: tran });
            const resultData1 = await this.ctx.model.Advert.update({ advert_order }, { where: { advert_id: targetAdvertId }, transaction: tran });
            if (resultData[0] <= 0 || resultData1[0] <= 0) {
                throw new Error('移动失败');
            }
            await tran.commit();
        } catch (e) {
            await tran.rollback();
            this.ctx.logger.error(e);
            throw new Error(JSON.stringify({ code: 2, msg: '移动失败' }));
        }
    }
}
export default AdvertService;